package com.xky.ui.module.warehouseManagement;

import com.xky.pojo.Warehouses;
import com.xky.ui.module.warehouseManagement.select.WarehouseService;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static com.xky.ui.main.MainView.*;

public class WarehouseInfo {

    private static JTable warehouseTable;
    
    /**
     * 显示仓库信息页面
     */
    public static void showWarehouseInfoPage() {
        // 创建仓库信息面板
        JPanel warehouseInfoPanel = WarehouseManage.createWarehouseInfoPanel(WarehouseInfo::refreshWarehouseData);

        // 获取表格组件
        Component[] components = ((JScrollPane)warehouseInfoPanel.getComponent(1)).getViewport().getComponents();
        if (components.length > 0 && components[0] instanceof JTable) {
            warehouseTable = (JTable) components[0];
        }

        // 更新右侧面板
        rightPanel.removeAll();
        rightPanel.add(warehouseInfoPanel, BorderLayout.CENTER);
        rightPanel.revalidate();
        rightPanel.repaint();

        // 注册刷新操作
        registerRefreshAction("仓库信息", WarehouseInfo::refreshWarehouseData);

        // 立即刷新一次
        refreshWarehouseData();
    }

    /**
     * 刷新仓库数据
     */
    static void refreshWarehouseData() {
        new SwingWorker<List<Warehouses>, Void>() {
            @Override
            protected List<Warehouses> doInBackground() {
                return WarehouseService.selectAllWarehouses();
            }

            @Override
            protected void done() {
                try {
                    List<Warehouses> warehouses = get();
                    if (warehouseTable != null) {
                        // updateTableData方法会清空并更新表格数据
                        WarehouseManage.updateTableData(warehouseTable, warehouses);
                        rightPanel.revalidate();
                        rightPanel.repaint();
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "刷新失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }.execute();
    }
} 